於~\src\components\ 下新增
一個ProductDetails.js 元件
~\src\components\ProductDetails.js 程式碼
在此故意做個錯誤示範(缺少return)
import React, { Component } from 'react';
export default class ProductDetails extends Component {
render() {
<div>Product Details</div>
}
}
再到
~\src\App.js
添加元件路由
~\src\App.js 程式碼
import React, { Component } from 'react';
import { Route } from 'react-router';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import { FetchData } from './components/FetchData';
import { Counter } from './components/Counter';
import ProductDetails from './components/ProductDetails';
import './custom.css'
export default class App extends Component {
static displayName = App.name;
render() {
return (
<Layout>
<Route exact path='/' component={Home} />
<Route path='/counter' component={Counter} />
<Route path='/fetch-data' component={FetchData} />
<Route path='/product/details' component={ProductDetails} />
</Layout>
);
}
}
運行後報錯
Compiled with problems:X
ERROR
src\components\ProductDetails.js
Line 3:5: Your render method should have a return statement react/require-render-return
Search for the keywords to learn more about each error.
直接回到該支元件程式碼中去做修正
不用停用vs運行會自動hot reload
這裡借用一個placeholder
https://via.placeholder.com/600
調整詳細頁顯示
與增添此元件所需的屬性
~\src\components\ProductDetails.js 程式碼
import React, { Component } from 'react';
export default class ProductDetails extends Component {
constructor(props) {
super(props);
this.state = { name: 'Some interesting product', description: 'this is the product', price: 130 };
}
render() {
return <div className="row">
<div className="col-12">
<div className="media">
<img src="https://via.placeholder.com/600" className="mr-3" alt="Product" />
<div className="media-body">
<h1>{this.state.name}</h1>
<p>{this.state.description}</p>
<p>£{this.state.price}</p>
</div>
</div>
</div>
</div>
}
}
運行效果
本篇以同步發表至個人blog
https://coolmandiary.blogspot.com/2022/09/net-corereact03.html